<template>
  <div class="app-container">
    <el-form :inline="true" label-width="100px">
      <!-- <el-form-item label="时间范围">
        <el-date-picker
          v-model="form.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 300px;"
        />
      </el-form-item> -->

      <el-form-item label="时间范围"  label-width="100">
        <el-date-picker
          v-model="form.timeRange"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date(2023, 2, 1, 0, 0,0,0), new Date(2023, 2, 5, 23, 59,59,0)]"
          align="right"
        >
        </el-date-picker>
      </el-form-item>


      <el-form-item label="区域">
        <el-select v-model="form.region" placeholder="请选择区域" @change="onRegionChange" style="width: 150px;">
          <el-option
            v-for="region in areaList"
            :key="region.areaCode"
            :label="region.areaName"
            :value="region.areaCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="线路">
        <el-select v-model="form.line" placeholder="请选择线路" @change="onLineChange" style="width: 150px;">
          <el-option
            v-for="line in lineList"
            :key="line.id"
            :label="line.lineName"
            :value="line.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="杆号">
        <el-select v-model="form.pole" placeholder="请选择杆号"  @change="onPoleChange" style="width: 150px;">
          <el-option
            v-for="pole in poleList"
            :key="pole.id"
            :label="pole.poleCode"
            :value="pole.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="点位">
        <el-select v-model="form.point" placeholder="请选择点位"  style="width: 150px;">
          <el-option
            v-for="point in pointList"
            :key="point.pointName"
            :label="point.pointName"
            :value="point.pointName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="相位">
        <el-select v-model="form.phase" placeholder="请选择相位" style="width: 150px;">
          <el-option value="" label="全部" />
          <el-option
            v-for="phase in phases"
            :key="phase"
            :label="phase"
            :value="phase"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
      </el-form-item>
    </el-form>

    <div id="chart" style="width: 100%; height: 400px; margin-top: 20px;"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { selectAllAreaList,getInfoByAreaCode } from "@/api/line/area.js";
import { selectAllLineList } from "@/api/line/line.js";
import { selectAllPoleList,getPole } from "@/api/line/pole.js";
import { selectAllPointDeviceList } from "@/api/line/point.js";
import { selectAllTemperatureList } from "@/api/line/temperature.js";
import { formatDate } from "@/utils/date";


export default {
  data() {
    return {
      form: {
        areaList:[],
        lineList:[],
        poleList:[],
        pointList:[],
        timeRange: [],
        region: "",
        line: "",
        pole: "",
        phase: "",
        poleId: null,
        poleName:null,
        areaName:null,
        areaInfo:null,
      },
      lines: [],
      poles: [],
      phases: ["A", "B", "C"],
      chartInstance: null,
      chartData: [],
    };
  },
  created(){
      this.selectAllAreaList();
  },
  methods: {
    getInfoByAreaCode(value){
      getInfoByAreaCode(value).then(response => {
        if(response.data != null){
          this.areaInfo = response.data
        }
      });
    },

     handleChartClick() {
        this.getInfoByAreaCode(this.form.region);
        getPole(this.form.pole).then(response => {
        if(response.data != null){
          // 跳转页面并传递参数
      this.$router.push({
         path: this.redirect || "/temperature/baidu",           
         query:{
            poleLongitude : response.data.poleLongitude,
            poleLatitude : response.data.poleLatitude,
            poleStatus : response.data.alarmStatus,
            alarmInformation :  response.data.alarmInformation,
            content :  response.data.poleName,
          }}).catch(()=>{});
          }
      });

       
    },
    selectAllAreaList(){
      selectAllAreaList().then(response => {
        this.areaList = response.data;
      });
    },
    onRegionChange(value) {
  return new Promise((resolve) => {
    const queryParams = { areaCode: value };
    selectAllLineList(queryParams).then(response => {
      this.lineList = response.data;
      this.form.line = ""; // 清空已选中的线路
      this.poles = [];
      resolve();
    });
  });
},
onLineChange(value) {
  return new Promise((resolve) => {
    const queryParams = { lineId: value };
    selectAllPoleList(queryParams).then(response => {
      this.poleList = response.data;
      resolve();
    });
  });
},

onPoleChange(value) {
  return new Promise((resolve) => {
    const queryParams = { poleId: value };
    selectAllPointDeviceList(queryParams).then(response => {
      this.pointList = response.data;
      resolve();
    });
  });
},
    // onPointChange(value) {
    //   this.form.point = value.pointName;
    //   this.pointId = value.id
    // },
    async queryData() {
      this.chartInstance.clear();
      // this.initChart();
      
      const { phase, pole, point } = this.form;
      var result = {};
      // 如果选择了特定的相位，只显示该相位的数据
      if (phase) {
        result = await this.selectAllTemperatureList();
        console.log("result的结果："+result);
        this.chartData = [{ name: phase, pole, point, data: result.currentTemperatures }];
      } else {
        // 如果没有选择相位，显示所有相位的数据
        result = await this.selectAllTemperatureList("A");
        var resultB = await this.selectAllTemperatureList("B");
        var resultC = await this.selectAllTemperatureList("C");

        this.chartData = [
          { name: "A", pole,point, data: result.currentTemperatures },
          { name: "B", pole,point, data: resultB.currentTemperatures },
          { name: "C", pole,point, data: resultC.currentTemperatures },
        ];
      }

      this.updateChart(result.reportTimes);
    },
   selectAllTemperatureList(phase){
      debugger
      return new Promise((resolve) => {
      var point = this.form.point.split('-');
      
      var queryParams = {
        pointName:point[1],
        pointDeviceName:point[0],
        poleId:this.form.pole,
        phase: phase == null ? this.form.phase : phase,
        startReportTime: (this.form.timeRange == null || this.form.timeRange.length == 0 ||  this.form.timeRange[0] === "") ? null
          : formatDate(this.form.timeRange[0], "yyyy-MM-dd hh:mm:ss"),
        endReportTime:(this.form.timeRange == null || this.form.timeRange.length == 0 ||  this.form.timeRange[1] === "")  ? null
          : formatDate(this.form.timeRange[1], "yyyy-MM-dd hh:mm:ss"),
        }
        
        selectAllTemperatureList(queryParams).then((response) => {
          if (response.code === 200) {
            resolve(response.data);
          }
        });
      });
    },

    generateTemperatureData() {
      return Array.from({ length: 24 }, () =>
        (Math.random() * 50 - 10).toFixed(1)
      );
    },
    initChart() {
      this.chartInstance = echarts.init(document.getElementById("chart"));
      this.updateChart();
    },
    updateChart(value) {
      const option = {
        title: { text: "温度变化图" },
        tooltip: {
          trigger: "axis", // 触发坐标轴
          backgroundColor: "#ffeb3b", // 背景色为黄色
          borderColor: "#fff", // 边框颜色
          borderWidth: 1,
          textStyle: { color: "#000" }, // 字体颜色为黑色
          formatter: (params) => {
            const time = params[0]?.axisValueLabel; // 获取时间
            let tooltipHtml = `<strong>${time}</strong><br/>`;

            // 显示所有相位（A, B, C）的温度
            params.forEach((item) => {
              if (item.seriesName === "A") {
                tooltipHtml += `A相: 温度: ${item.data}°C<br/>`;
              } else if (item.seriesName === "B") {
                tooltipHtml += `B相: 温度: ${item.data}°C<br/>`;
              } else if (item.seriesName === "C") {
                tooltipHtml += `C相: 温度: ${item.data}°C<br/>`;
              }
            });

            return tooltipHtml;
          },
        },
        legend: { data: this.chartData.map((item) => item.name) },
        xAxis: {
          type: "category",
          data: (value == null || value == undefined)  ? Array.from({ length: 24 }, (_, i) => `${i}:00`)  : value,
        },
        yAxis: {
          type: "value",
          name: "温度 (°C)",
          axisLabel: { formatter: "{value}°C" },
        },
        series: this.chartData.map((item) => ({
          name: item.name,
          type: "line",
          data: item.data,
        })),
      };
      this.chartInstance.setOption(option);
    },
  },
  mounted() {
        this.initChart();
        const query = this.$route.query;
        if(this.$route.query.areaCode != null 
        && this.$route.query.lineId != null
        && this.$route.query.poleId != null
        && this.$route.query.pointDeviceName != null
        && this.$route.query.pointName != null
        && this.$route.query.startTime != null
        && this.$route.query.endTime != null){
         // 初始化区域选项
    selectAllAreaList().then(() => {
      this.form.region = query.areaCode;
      this.onRegionChange(this.form.region).then(() => {
        // 初始化线路选项
        this.form.line = query.lineId;
        this.onLineChange(this.form.line).then(() => {
          // 初始化杆号选项
          this.form.pole = query.poleId;
          this.onPoleChange(this.form.pole).then(() => {
            // 初始化点位选项
            this.form.point = `${query.pointDeviceName}-${query.pointName}`;
            // 初始化时间范围
            this.form.timeRange = [
              new Date(query.startTime),
              new Date(query.endTime)
            ];
            // 查询数据
            this.queryData();
          });
        });
      });
    });
        }

         // 监听点击事件
        this.chartInstance.on('click', (params) => {
        console.log('点击的数据:', params); // 打印点击的数据，方便调试
        this.handleChartClick(params);
    });

        
  },
};
</script>

<style scoped>
#chart {
  border: 1px solid #ebeef5;
  border-radius: 5px;
}
</style>
